<?php
declare (strict_types = 1);

namespace app\admin\controller\maichen;

use think\Request;
use app\admin\model\Purchase;
use think\facade\Request as Rq;
use think\facade\View;
use think\facade\Session;
use think\facade\Db;
use app\admin\validate\maichen\Purchase as Pv;
use app\admin\model\Purchase as Pm;
use app\common\controller\Base;
use app\admin\model\Adjustment as Am;
use app\admin\model\CustomerQuotation as CQm;
use app\admin\model\Customer as Cm;
use app\admin\model\Sku;
use app\admin\validate\maichen\Adjustment as Av;
use app\admin\validate\maichen\Customer as Cv;
use app\admin\validate\maichen\Supply as Sv;
use app\admin\model\Customer as CustomerModel;
use app\common\controller\Backend;
use lemo\helper\ExcelHelper;

class Supply extends Base
{
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        if (Rq::isPost()) {
            $key = Rq::post('keys', '', 'trim');
            $page = Rq::post('page', 1);
            $pagesize = Rq::post('limit', 15);
           
            $model = new Purchase();
            $where0 = [['name', 'like', "%{$key}%"]];
            $where1 = [['material', 'like', "%{$key}%"]];
            $where2 = [['manufacturer', 'like', "%{$key}%"]];
            $list = Purchase::with('adjustment')->whereOr([$where0, $where1, $where2])->paginate(['list_rows' => $pagesize, 'page' => $page])->toArray();
            // halt($list);
            return ['code' => 0, 'msg' => lang('get info success'), 'data' => $list['data'], 'count' => $list['total']];
        }
        return view();
    }

    /**
     * 显示创建资源表单页.
     *
     * @return \think\Response
     */
    public function create()
    {
        //
    }

    /**
     * 保存新建的资源
     *
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function add(Request $request)
    {
        if (Rq::isPost()) {
            $admin= Session::get('admin.username');
            $data = Rq::only(['name', 'material', 'manufacturer', 'pic', 'buying_price', 'price_adjustment_date', 'num', 'box_gauge', 'notes']);
            try {
                validate(Pv::class)->check($data);
                $data['uid'] =  $admin;
                $pm = Pm::create($data);
                $am = new Am();
                $am_data = [
                    'price_adjustment_date'=> $data['price_adjustment_date'],
                    'price' => $data['buying_price'],
                    'user' => $admin,
                    'purchase_id' => $pm->id,
                ];
                $am->save($am_data);
                if ($pm->id) {
                    $this->success(lang('add success'), url('maichen.Supply/index'));
                }
            } catch (ValidateException $e) {
                $this->error( $e->getError());
            }
        }
        $view = [
            'title' => '产品',
            'info' => [],
        ];

        View::assign($view);
        return view();  
    }

    /**
     * 显示指定的资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function read($id)
    {
        //
    }

    /**
     * 显示编辑资源表单页.
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function edit($id)
    {
        if (Rq::isPost()) {
            $admin= Session::get('admin.username');
            $data = Rq::only(['name', 'material', 'manufacturer', 'pic', 'num', 'box_gauge', 'notes']);
            try {
                validate(Pv::class)->scene('edit')->check($data);
                $data['uid'] =  $admin;
                $data['id'] = Rq::post('id');
                $pm = Pm::update($data);
                if ($pm) {
                    $this->success(lang('add success'), url('maichen.Supply/index'));
                }
            } catch (ValidateException $e) {
                $this->error( $e->getError());
            }
        } else {
            $id = Rq::param('id');
            $info = Pm::find($id);
            $view = [
                'info' => $info,
                'id' => $id,
            ];
            View::assign($view);
            return view();
        }
    }

    /**
     * 保存更新的资源
     *
     * @param  \think\Request  $request
     * @param  int  $id
     * @return \think\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete($id)
    {
        $ids = Rq::post('ids');
        if (!empty($ids)) {
            Pm::destroy($ids);
            $this->success(lang('delete success'));
        } else {
            $this->error(lang('supper man cannot delete'));
        }
    }

    public function addAdjustment() {
        $id = Rq::get('id');
        if (Rq::isPost()) {
            $id = Rq::post('id');
            $data = Rq::only(['price', 'price_adjustment_date']);
            $data['purchase_id'] = $id;
            $data['user']= Session::get('admin.username');
            try {
                validate(Av::class)->check($data);
                $model = new Am();
                $result = $model->save($data);
                $pdata = [
                    'id' => $id,
                    'buying_price' => $data['price'],
                    'price_adjustment_date' => $data['price_adjustment_date'],
                    'uid' => Session::get('admin.username'),
                ];
                Pm::update($pdata);
                if ($result) {
                    $this->success(lang('add success'), url('maichen.Supply/index'));
                } else {
                    $this->error('添加失败');
                }
            } catch(ValidateException $e) {
                $this->error( $e->getError());
            }
            
            
        }
        $view = [
            'title' => '产品',
            'id' => $id,
        ];

        View::assign($view);
        return view();  
    }

    public function customerQuotation()
    {
        if (Rq::isPost()) {
            $key = Rq::post('keys', '', 'trim');
            $page = Rq::post('page', 1);
            $pagesize = Rq::post('limit', 15);
            $where0 = [['customer_name', 'like', "%{$key}%"]];
            $list = CQm::whereOr([$where0])->paginate(['list_rows' => $pagesize, 'page' => $page])->toArray();
            return ['code' => 0, 'msg' => lang('get info success'), 'data' => $list['data'], 'count' => $list['total']];
        }
        return view();
    }

    public function addCustomerQuotation()
    {
        if (Rq::isPost()) {
            $dd = Rq::only(['shop_no', 'customer_name']);
            try {
                validate(Sv::class)->check($dd);
                $cqm = new CQm();
                $result = $cqm->save($dd);
                if ($result) {
                    $this->success(lang('add success'), url('maichen.Supply/customerQuotation'));
                } else {
                    $this->error('添加失败');
                }
                
            } catch (ValidateException $e) {
                $this->error($e->getError());
            }
        }
        return view();
    }

    public function customer() {
        $id = Rq::get('id');
        if (Rq::isPost()) {
            $page = Rq::post('page', 1);
            $pagesize = Rq::post('limit', 15);
            $id = Rq::post('id');
            // $list = Cm::where('id', 1)->select();
            // $list = Db::name('customer')->where('cqid', $id)->paginate(['list_rows' => $pagesize, 'page' => $page])->toArray();
            $list = Cm::with('sku')->where('cqid', $id)->paginate(['list_rows' => $pagesize, 'page' => $page])->toArray();
            // echo Db::getLastSql();exit;
            return ['code' => 0, 'msg' => lang('get info success'), 'data' => $list['data'], 'count' => $list['total']];
        }
        $view = [
            'id' => $id,
        ];
        View::assign($view);
        return view();
    }

    public function addCustomer() {
        $id = Rq::get('id');
        if (Rq::isPost()) {
            $admin= Session::get('admin.username');
            $data = Rq::only(['product_name', 'physical_pic', 'specifications_pic', 'attribute', 'quotation_pic', 'purchasing_cost', 'consumables', 'artificial', 'cargo_damage', 'unit', 'notes', 'price_adjustment_date', 'freight_remarks', 'manufactor', 'product_type']);
            $cqid = Rq::post('id');
            $data['cqid'] = $cqid;
            try {
                validate(Cv::class)->check($data);
                $model = new Cm();
                $data['user'] =  $admin;
                $result = $model->save($data);
                if ($result) {
                    $this->success(lang('add success'), url('maichen.Supply/customer?id='.$cqid));
                }
            } catch (ValidateException $e) {
                $this->error( $e->getError());
            }
        }
        $view = [
            'title' => '客户报价表',
            'info' => [],
            'id' => $id
        ];

        View::assign($view);
        return view();  
    }

    public function editCustomer() {
        if (Rq::isPost()) {
            $admin= Session::get('admin.username');
            $data = Rq::only(['product_name', 'physical_pic', 'specifications_pic', 'attribute', 'quotation_pic', 'purchasing_cost', 'consumables', 'artificial', 'cargo_damage', 'unit', 'id', 'notes', 'price_adjustment_date', 'freight_remarks', 'manufactor', 'product_type']);
            try {
                validate(Cv::class)->check($data);
                // $model = new Cm();
                $data['user'] =  $admin;
                // halt($data['physical_pic']);
                $result = Cm::update($data);
                $cqid = Cm::field('cqid')->find($data['id'])->toArray();
                if ($result) {
                    $this->success(lang('edit success'), url('maichen.Supply/customer?id='.$cqid['cqid']));
                }
            } catch (ValidateException $e) {
                $this->error( $e->getError());
            }
        } else {
            $id = Rq::param('id');
            $info = Cm::find($id);
            $view = [
                'info' => $info,
                'id' => $id,
            ];
            View::assign($view);
            return view();
        }
    }

    public function addSku()
    {       
        if (Rq::isPost()) {
            $data = Rq::post('data');
            foreach ($data as $key => $value) {
                unset($data[$key]['LAY_TABLE_INDEX']);
            }
            $sku = new Sku();
            $result = $sku->saveAll($data);
            if ($result) {
                $customerInfo = Cm::find($data[0]['customer_id'])->toArray();
                //$this->success(lang('add success'), url('maichen.Supply/customer?id='.$customerInfo['cqid']));
                $res = [
                    'code' => 1,
                    'msg' => '添加成功',
                    'id' => $customerInfo['cqid'],
                ];
            } else {
                //$this->error('添加失败');
                $res = [
                    'code' => 2,
                    'msg' => '添加失败',
                ];
            }
            return json($res);
        } else {
        }
        $view = [
            'title' => '添加 sku',
            'id' =>  Rq::get('id'),
        ];
        View::assign($view);
        return view();
    }

        /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delCustomer()
    {
        $ids = Rq::post('ids');
        if (!empty($ids)) {
            $result = Cm::destroy($ids);
            if ($result) {
                $this->success(lang('delete success'));
            } else {
                $this->error('删除失败');
            }
           
        } else {
            $this->error(lang('supper man cannot delete'));
        }
    }


    public function changeStatus() {
        $group_id = Session::get('admin.group_id');
        $group = ['1'];
        
        if (in_array($group_id, $group)) {
            $id = Rq::get('id');
            $customer = Cm::find($id);
            $customer->status = 1;
            $result = $customer->save();
            if ($result) {
                $this->success('审核成功', url('maichen.Supply/customer?id='.$customer->cqid));
            } else {
                $this->error('审核失败');
            }
        } else {
            $this->error('没有权限审核状态');
        }
    }

    public function importExcel()
    {
        if ($this->request->isPost()) {
            $file = request()->file('file');
            if (!$file) {
                return json(['code' => 1, 'msg' => '请选择文件']);
            }

            try {
                // 验证文件
                // validate(['file' => 'fileSize:20240|fileExt:xlsx,xls'])->check(['file' => $file]);
                
                // 保存文件
                $savename = \think\facade\Filesystem::disk('public')->putFile('excel', $file);
                $filePath = public_path() . 'storage/' . $savename;

                // 读取Excel
                $data = \lemo\helper\ExcelHelper::import($filePath, 2); // 从第2行开始读取数据
                halt($data);
                // 处理数据
                $success = 0;
                $error = 0;
                foreach ($data as $row) {
                    try {
                        $customer = new CustomerModel();
                        $customer->name = $row[0] ?? ''; // 客户名称
                        $customer->phone = $row[1] ?? ''; // 联系电话
                        $customer->address = $row[2] ?? ''; // 地址
                        $customer->save();
                        $success++;
                    } catch (\Exception $e) {
                        $error++;
                    }
                }

                // 删除临时文件
                @unlink($filePath);

                return json([
                    'code' => 0,
                    'msg' => "导入完成，成功：{$success}条，失败：{$error}条",
                    'data' => ['filename' => $file->getOriginalName()]
                ]);
            } catch (\Exception $e) {
                return json(['code' => 1, 'msg' => $e->getMessage()]);
            }
        }

        return json(['code' => 1, 'msg' => '非法请求']);
    }

    public function changePStatus() 
    {
        $r = [
            'code' => 0,
            'msg' => '成功审核',
        ];
        $group_id = Session::get('admin.group_id');
        $group = ['1'];
        
        if (in_array($group_id, $group)) {
            $id = Rq::get('id');
            $pm = Pm::find($id);
            $pm->status = 1;
            $result = $pm->save();
            if ($result) {
                // $this->success('审核成功', url('maichen.Supply/index'));
            } else {
                $r = [
                    'code' => 1,
                    'msg' => '审核失败',
                ];
            }
        } else {
            $r = [
                'code' => 2,
                'msg' => '没有权限',
            ];
        }

        return json($r);
    }
}
